#!/usr/bin/env ruby
require 'fileutils'

unless defined? ROR_SERVICE_ROOT
  ROR_SERVICE_ROOT = File.expand_path(File.join(File.dirname(__FILE__), '..'))
  $:.unshift(ROR_SERVICE_ROOT)
end

class HAProxyController

  include FileUtils

  def initialize
    @pid_file = File.join(ROR_SERVICE_ROOT, 'config', 'haproxy.pid')
    @haproxy_conf = File.join(ROR_SERVICE_ROOT, 'config', 'haproxy.conf')
  end

  def pids
    return nil unless File.file?(@pid_file)
    File.readlines(@pid_file).map { |pid| pid.chomp }.join(' ')
  end

  def restart
    puts "#{Time.now.strftime('%H:%M:%S')} Restarting HAProxy."
    old_pids = pids()
    if old_pids
      puts "Killing old processes: #{old_pids}"
    else
      puts ".pid file not found"
    end
    commandline = "haproxy -D -f #{@haproxy_conf} -p #{@pid_file} #{old_pids ? "-sf #{old_pids}" : ''}"
    puts "restarting haproxy with command:  #{commandline}"
    puts `#{commandline}`
    raise "HAProxy failed to start" unless $?.success?
    puts "#{Time.now.strftime('%H:%M:%S')} Restarted HAProxy. New PID(s): #{pids}"
  end
end

if $0 == __FILE__
  HAProxyController.new.restart
end
